﻿CREATE PROCEDURE [ServiceEngine].[DeleteOperationVersion]
	@ID uniqueidentifier
AS
BEGIN
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	SET NOCOUNT ON;

	BEGIN TRY
		BEGIN TRANSACTION

		DECLARE @OPID uniqueidentifier

		SELECT  @OPID = OV.OperationID
		FROM	[ServiceEngine].OperationVersions OV
		WHERE	OV.OperationVersionID = @ID

		SELECT  @@ROWCOUNT
		FROM	[ServiceEngine].OperationVersions OV
		WHERE	OV.OperationID = @OPID


		IF @@ROWCOUNT = 1 -- last Version so Delete master "operation"
		BEGIN
			DELETE	ServiceEngine.Operations 
			WHERE	OperationID = @OPID

			DELETE	ServiceEngine.Names
			WHERE	EntityID = @OPID and EntityTypeID = 4
		END

		DELETE	OperationVersions
		WHERE	OperationVersionID = @ID

		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();

		IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;

		RAISERROR (@ErrorMessage, 
				   @ErrorSeverity,
				   1);
	END CATCH
END